package com.yangj.util;

import java.net.*;
import java.io.*;
import java.util.*;
import java.security.*;

public class MyUtils
{
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent;
    
    static {
        MyUtils.userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    }
    
    //post请求
    public static String post(final String url, final String data) {
        try {
            final URL urlObj = new URL(url);
          //打开连接
            final URLConnection connection = urlObj.openConnection();
            connection.setDoOutput(true);
            final OutputStream os = connection.getOutputStream();
            os.write(data.getBytes());
            os.close();
            final InputStream is = connection.getInputStream();
            final StringBuilder sb = new StringBuilder();
            final byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            System.out.println("sb: " + sb.toString());
            return sb.toString();
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /*
     * 发送get请求
     * */
    public static String get(final String url) {
        try {
            final URL urlObj = new URL(url);
            //打开连接
            final URLConnection connection = urlObj.openConnection();
            final InputStream is = connection.getInputStream();
            final StringBuilder sb = new StringBuilder();
            final byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b)) != -1) {
                sb.append(new String(b, 0, len));
            }
            return sb.toString();
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static String net(String strUrl, final Map params, final String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            final StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = String.valueOf(strUrl) + "?" + urlencode(params);
            }
            System.out.println("URL: " + strUrl);
            final URL url = new URL(strUrl);
            conn = (HttpURLConnection)url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            }
            else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", MyUtils.userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    final DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                }
                catch (Exception ex) {}
            }
            final InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        }
        catch (IOException e) {
            e.printStackTrace();
            return rs;
        }
        finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        if (reader != null) {
            reader.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
        return rs;
    }
    
    //map 转url
    public static String urlencode(final Map<String, Object> data) {
        final StringBuilder sb = new StringBuilder();
        for (final Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(new StringBuilder().append(i.getValue()).toString(), "UTF-8")).append("&");
            }
            catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    
    /*
     * 获取签名
     * */
    public static Map<String, String> getSignature(final Map<String, String> tempParamS, final String app_key) throws IOException {
    	//将<key,value>请求参数对 按key字典序升序排序，得到有序的参数列表对列表
        Map<String, String> sortedParams = new TreeMap<String, String>(tempParamS);
        Set<Map.Entry<String, String>> entrys = sortedParams.entrySet();
        StringBuilder baseString = new StringBuilder();
        for ( Map.Entry<String, String> param : entrys) {
            if (param.getValue() != null && !"".equals(param.getKey().trim()) && !"sign".equals(param.getKey().trim()) && !"".equals(param.getValue())) {
                baseString.append(param.getKey().trim()).append("=").append(URLEncoder.encode(param.getValue().toString(), "UTF-8")).append("&");
            }
        }
        //将应用密钥以app_key为键名，组成URL键值拼接到字符串T末尾，得到字符串S
        if (baseString.length() > 0) {
            baseString.deleteCharAt(baseString.length() - 1).append("&app_key=").append(app_key);
        }
        try {
        	//md5加密
            String sign = md5Encrype(baseString.toString());
            sortedParams.put("sign", sign);
        }
        catch (Exception ex) {
            throw new IOException(ex);
        }
        return sortedParams;
    }
    
    /*
     * md5 加密
     * */
    private static String md5Encrype(final String str) {
        StringBuilder sb = new StringBuilder();
        try {
        	//获取一个加密对象
            MessageDigest md5 = MessageDigest.getInstance("md5");
            byte[] digest = md5.digest(str.getBytes());
            char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            for (int i = 0; i < digest.length; ++i) {
                final byte b = digest[i];
                sb.append(hexChar[b >> 4 & 0xF]);
                sb.append(hexChar[b & 0xF]);
            }
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    /*
     * sha1加密
     * */
    public static String sha1Encrype(final String str) {
        StringBuilder sb = new StringBuilder();
        try {
        	//获取一个加密对象
            MessageDigest md = MessageDigest.getInstance("sha1");
            //加密 1个字节 =8位
            byte[] digest = md.digest(str.getBytes());
            char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
            //处理加密结果
            for (int i = 0; i < digest.length; ++i) {
                final byte b = digest[i];
                //高4位
                sb.append(hexChar[b >> 4 & 15]);
                //低4位
                sb.append(hexChar[b & 15]);
            }
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}
